package cn.wolfcode.trip.api.controller;

import cn.wolfcode.trip.base.domain.*;
import cn.wolfcode.trip.base.query.ProductQueryObject;
import cn.wolfcode.trip.base.service.*;
import cn.wolfcode.trip.base.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Copyright: Copyright (c) 2019 Super520
 * 描述：商品接口
 *
 * @package: cn.wolfcode.trip.api.controller
 * @author: Patch
 * @date: 2019/6/1 17:33
 * 总结:
 */
@RestController
@RequestMapping("shop")
public class ProductContrller {
    @Autowired
    private IProductService productService;
    @Autowired
    private IShopCartService cartService;
    @Autowired
    private IShopOrderService orderService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IIntegralService integralService;
    @Autowired
    private IProductDirService dirService;

    /**
     * 高级查询获取对应条件商品接口
     * 1.资源 /shop/products
     * 2.请求方式 post
     * 3.请求参数 无
     * 4.返回结果 JsonResult
     *
     * @return
     */
    @GetMapping("products")
    public Object list(ProductQueryObject qo) {
        // 查询已发布的商品
        qo.setStatus(1);
        // 设置排序
        qo.setOrderBy("p.sequence asc");
        return productService.queryForApp(qo);
    }

    /**
     * 获取指定的商品信息
     * 1.资源  /shop/product/{id}
     * 2.方式 get
     * 3.参数 id
     * 4. 返回商品对象的JSON数据
     */
    @GetMapping("product/{id}")
    public Object getProduct(@PathVariable Long id) {
        return productService.getProductById(id);
    }

    /**
     * 查询指定用户购物车信息
     * 1.资源  /shop/cart/user/{uId}
     * 2.方式 get
     * 3.参数 uId 用户id
     * 4. 返回购物车对象的JSON数据
     */
    @GetMapping("product/user/{uId}")
    public Object listAllByUserId(@PathVariable("uId") Long uId) {
        return cartService.listAllByUserId(uId);
    }

    /**
     * 添加指定物品到购物车
     * 1.资源  /shop/product
     * 2.方式 post
     * 3.参数 uId 用户id,商品id
     * 4.返回 jsonresult
     */
    @PostMapping("product")
    public Object saveCart(ShopCart shopCart) {
        JsonResult result = new JsonResult();
        try {
            cartService.saveOrUpdate(shopCart);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("亲，操作失败");
        }
        return result;
    }

    /**
     * 清空购物车商品
     */
    @DeleteMapping("product/user/{uId}")
    public Object deleteAll(@PathVariable Long uId) {
        JsonResult result = new JsonResult();
        try {
            cartService.deleteAll(uId);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("亲，操作失败");
        }
        return result;
    }

    /**
     * 添加订单
     */
    @PostMapping("order/{uId}")
    public Object addOrder(@PathVariable Long uId, Integer totalPrice) {
        System.out.println(totalPrice);
        List<Map<String, Object>> all = cartService.listAllByUserId(uId);
        for (Map<String, Object> map : all) {
            ShopOrder order = new ShopOrder();
            order.setTotalPrice(totalPrice);
            order.setCreateTime(new Date());
            order.setNum(Integer.valueOf(map.get("totalNum").toString()));
            Product product = (Product) getProduct(Long.valueOf(map.get("pId").toString()));
            order.setProduct(product);
            order.setUnitPrice(product.getPrice());
            User user = new User();
            user.setId(uId);
            order.setUser(user);
            orderService.saveOrUpdate(order);
        }
        JsonResult result = new JsonResult();
        try {
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("亲，操作失败");
        }
        return result;
    }

    /**
     * 支付
     */
    @PostMapping("pay/{uId}")
    public Object pay(@PathVariable Long uId, Integer totalPrice) {
        JsonResult result = new JsonResult();
        if (totalPrice <= 0) {
            result.mark("请先选择商品");
            return result;
        }
        try {
            List<Map<String, Object>> all = cartService.listAllByUserId(uId);
            for (Map<String, Object> map : all) {
                ShopOrder order = new ShopOrder();
                order.setTotalPrice(totalPrice);
                order.setCreateTime(new Date());
                order.setNum(Integer.valueOf(map.get("totalNum").toString()));
                Product product = (Product) getProduct(Long.valueOf(map.get("pId").toString()));
                order.setProduct(product);
                order.setUnitPrice(product.getPrice());
                User user = new User();
                user.setId(uId);
                order.setUser(user);
                orderService.saveOrUpdate(order);
                // 修改商品销量和库存
                productService.updateSalesNumAndStoreNumById(Long.valueOf(map.get("pId").toString()));
            }
            // 删除指定的购物车信息
            deleteAll(uId);
            // 扣除指定的积分
            userService.minusGrade(uId, totalPrice);
            // 添加扣除积分明细
            Integral integral = new Integral();
            integral.setGrade(-(totalPrice));
            integral.setInputTime(new Date());
            integral.setRemark("商品付款，扣除积分："+totalPrice);
            IntegralType type = new IntegralType();
            type.setId(6L);
            integral.setType(type);
            User user = new User();
            user.setId(uId);
            integral.setUser(user);
            integralService.saveOrUpdate(integral);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /**
     * 查询订单
     */
    @GetMapping("user/order/{uId}")
    public Object listAllByUid(@PathVariable Long uId) {
        return orderService.listAllByUid(uId);
    }

    /**
     * 查询所有父类商品
     */
    @GetMapping("listParentAll")
    public Object listParentAll() {
        // 查询所有的商品父类型
        return dirService.listParentAll();
    }

}
